package com.gallop.mq.core.template.handler;

import com.gallop.mq.core.template.handler.registry.MessageDeliveryHandlerRegistry;
import com.gallop.mq.core.template.handler.registry.RegistryPreprocessor;
import lombok.Builder;
import lombok.Data;

/**
 * MQ监听消息抽象处理器。统一封装各种MQ监听的回调。
 */
@FunctionalInterface
public interface MessageDeliveryHandler {

    /**
     * 处理MQ监听收到的消息
     * @param deliveryContext 消息到达时上下文。
     *                        在注册监听时，调用{@link MessageDeliveryHandlerRegistry#createListener(DeliveryContext)}传入，
     *                        当消息到达时以参数方式提供
     * @param deliveryType MQ消息类型标记。通过{@link RegistryPreprocessor#getDeliveryTypeProvider()}提供
     * @param rpcInfo MQ消息的RPC相关标记。通过{@link RegistryPreprocessor#getRpcInfoProvider()}提供
     * @param incoming MQ消息解包后的消息内容。
     */
    void handlerDelivery(DeliveryContext deliveryContext,
                         DeliveryType deliveryType,
                         RpcInfo<?> rpcInfo,
                         Object incoming);

    @Data
    @Builder
    class StringRpcInfo implements RpcInfo<String> {
        private String replyTo;
        private String correlationId;
    }

    @Data
    @Builder
    class CustomRpcInfo implements RpcInfo<Object> {
        private Object replyTo;
        private String correlationId;
    }

    interface RpcInfo<T> {

        default <R extends RpcInfo<?>> R as() {
            return (R) this;
        }

        void setReplyTo(T replyTo);

        T getReplyTo();

        void setCorrelationId(String correlationId);

        String getCorrelationId();
    }
}
